<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Draggable 示例</title>
    <!-- 引入 jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入 jQuery UI -->
    <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
    <!-- 引入 jQuery UI 的 CSS -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        #container {
            width: 500px;
            height: 300px;
            border: 2px solid #ccc;
            position: relative;
            background-color: #f9f9f9;
        }
        .draggable-item {
            width: 100px;
            height: 100px;
            background-color: #4CAF50;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: move; /* 拖拽光标 */
            position: absolute;
        }
        #add-item {
            padding: 10px 20px;
            margin-top: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        #add-item:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <div id="container">
        <div class="draggable-item">拖拽我</div>
    </div>
    <button id="add-item">添加元素</button>

    <script>
        $(document).ready(function () {
            // 初始化拖拽功能
            $(".draggable-item").draggable({
                containment: "#container", // 限制拖拽范围
                revert: "invalid", // 如果拖拽无效，元素会回到原位置
                cursor: "move", // 拖拽时的光标
                start: function (event, ui) {
                    console.log("拖拽开始");
                },
                stop: function (event, ui) {
                    console.log("拖拽结束");
                }
            });

            // 动态添加可拖拽元素
            $("#add-item").click(function () {
                const newItem = $('<div class="draggable-item">新元素</div>');
                $("#container").append(newItem);
                newItem.draggable({
                    containment: "#container",
                    revert: "invalid",
                    cursor: "move"
                });
            });
        });
    </script>
</body>
</html>